package com.wzy.wzyblog.service;


import com.wzy.wzyblog.NotFoundException;
import com.wzy.wzyblog.dao.TagRepository;
import com.wzy.wzyblog.po.Tag;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;

import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


@Service
public class TagServiceImpl implements TagService {

    @Autowired
    private TagRepository tagRepository;

    @Transactional
    @Override
    public Tag saveTag(Tag tag) {
        return tagRepository.save(tag);
    }

    @Override
    public List<Tag> listTag(String ids) {//获取id的集合
        return tagRepository.findAllById(convertToList(ids));//装换为list对象
    }

//    把字符串转变为一个数组的方法
    private List<Long> convertToList(String ids){
        List<Long> list = new ArrayList<>();//数组
        if (!"".equals(ids) && ids != null) {//非空
            String[] idarray = ids.split(",");//截取
            for (int i=0; i < idarray.length;i++) {//放进list中
                list.add(new Long(idarray[i]));
            }
        }
        return list;//返回list
    }




    @Transactional
    @Override
    public Tag getTag(Long id) {
        return tagRepository.findById(id).orElse(null);
    }

    @Override
    public Tag getTagByName(String name) {
        return tagRepository.findByName(name);
    }

    @Transactional
    @Override
    public Page<Tag> listTag(Pageable pageable) {
        return tagRepository.findAll(pageable);
    }

    @Override
    public List<Tag> listTag() {
        return tagRepository.findAll();
    }




    @Transactional
    @Override
    public Tag updateTag(Long id, Tag tag) {
        Tag t = tagRepository.findById(id).orElse(null);
        if (t == null) {
            throw new NotFoundException("不存在该标签");
        }
        BeanUtils.copyProperties(tag,t);
        return tagRepository.save(t);
    }



    @Transactional
    @Override
    public void deleteTag(Long id) {

        tagRepository.deleteById(id);
    }


    @Override
    public List<Tag> listTagTop(Integer size) {
//版本更新方法
        Sort sort= Sort.by(Sort.Direction.DESC, "blogs.size");
        Pageable pageable = PageRequest.of(0, size,sort );
        return tagRepository.findTop(pageable);
    }
}
